<script setup lang="ts">
import { ref } from 'vue';
import { notification } from 'ant-design-vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { Tree } from 'ant-design-vue';
import { computed } from 'vue';

import { getRolePermissions, updateRolePermissions } from '#/api/abp/role';
import type { PermissionGroupDto, PermissionDto } from '#/api/abp/role/types';
import { useUserStore } from '@vben/stores';

const emit = defineEmits<{ reload: [] }>();

const permissionGroups = ref<PermissionGroupDto[]>([]);
const checkedKeys = ref<string[]>([]);
const expandedKeys = ref<string[]>([]);

const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { name } = modalApi.getData() as { name: string };

    try {
      const resp = await getRolePermissions('R', name);
      // 过滤掉指定的权限组和包含 'ManageRoles' 或 'ManagePermissions' 的权限
      permissionGroups.value = resp.groups.map(group => {
        // 过滤掉指定的权限组
        if (['FeatureManagement', 'SettingManagement', 'AbpTenantManagement'].some(excludedName => group.name.includes(excludedName))) {
          return null;
        }
        // 过滤掉包含 'ManageRoles' 或 'ManagePermissions' 的权限
        group.permissions = group.permissions.filter(permission =>
          !['ManageRoles', 'ManagePermissions'].some(excludedName => permission.name.includes(excludedName))
        );
        return group;
      }).filter(group => group !== null) as PermissionGroupDto[]; // 移除过滤掉的组

      // 收集已授权的权限
      const grantedPermissions: string[] = [];
      const allGroups: string[] = [];

      permissionGroups.value.forEach(group => {
        allGroups.push(group.name);
        group.permissions.forEach(permission => {
          if (permission.isGranted) {
            grantedPermissions.push(permission.name);
          }
        });
      });

      checkedKeys.value = grantedPermissions;
      expandedKeys.value = allGroups;
    } catch (error) {
      console.error('获取权限失败:', error);
    } finally {
      modalApi.modalLoading(false);
    }
  },
});

// 构建树形数据
const treeData = computed(() => {
  return permissionGroups.value.map(group => {
    const groupNode = {
      title: group.displayName,
      key: group.name,
      children: [] as any[],
    };

    // 构建权限的映射，方便查找
    const permissionMap = new Map<string, any>();
    group.permissions.forEach(permission => {
      permissionMap.set(permission.name, {
        title: permission.displayName,
        key: permission.name,
        children: [] as any[],
      });
    });

    // 构建父子关系
    group.permissions.forEach(permission => {
      const permissionNode = permissionMap.get(permission.name);
      if (permission.parentName) {
        const parentNode = permissionMap.get(permission.parentName);
        if (parentNode) {
          // 如果有父权限，将当前权限添加到父权限的 children 中
          parentNode.children.push(permissionNode);
        } else {
          // 如果找不到父节点（可能是数据问题或父节点不在当前组），将其视为顶级权限
          groupNode.children.push(permissionNode);
        }
      } else {
        // 没有 parentName 的视为顶级权限（直接放在组下）
        groupNode.children.push(permissionNode);
      }
    });

    // 过滤掉已经是子节点的权限，只保留顶级权限作为组的直接子节点
    // 顶级权限是没有 parentName 的，或者虽然有 parentName 但其 parentName 不在当前组的权限列表中
    groupNode.children = groupNode.children.filter(node => {
      const originalPermission = group.permissions.find(p => p.name === node.key);
      return !originalPermission?.parentName || !permissionMap.has(originalPermission.parentName);
    });

    return groupNode;
  });
});

async function handleConfirm() {
  try {
    modalApi.lock(true);

    const { name } = modalApi.getData() as { name: string };

    // 构建权限更新数据
    const permissions: Array<{ name: string; isGranted: boolean }> = [];

    permissionGroups.value.forEach(group => {
      group.permissions.forEach(permission => {
        permissions.push({
          name: permission.name,
          isGranted: checkedKeys.value.includes(permission.name),
        });
      });
    });

    await updateRolePermissions('R', name, { permissions });

    emit('reload');
    modalApi.close();

    notification.success({
      duration: 2,
      message: '权限更新成功,即将刷新页面',
      onClose: () => {
        // 获取当前用户信息
        const currentUser = useUserStore().userInfo;
        // 检查当前用户是否是被授权的角色
        if (currentUser?.roles?.includes(name)) {
          // 如果是当前用户，刷新页面
          window.location.reload();
        }
      },
    });
  } catch (error) {
    console.error('更新权限失败:', error);
  } finally {
    modalApi.lock(false);
  }
}

function handleClosed() {
  permissionGroups.value = [];
  checkedKeys.value = [];
  expandedKeys.value = [];
}

function onCheck(checkedKeysValue: string[]) {
  checkedKeys.value = checkedKeysValue;
}
</script>

<template>
  <BasicModal class="min-h-[600px] w-[800px]" title="权限管理">
    <div class="h-[500px] overflow-auto">
      <Tree v-model:checkedKeys="checkedKeys" v-model:expandedKeys="expandedKeys" :tree-data="treeData" checkable
        @check="(checked: any) => onCheck(checked as string[])" />
    </div>
  </BasicModal>
</template>
